{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 百度语音识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "#!/usr/bin/env python\n",
    "# -*- coding: utf-8 -*-\n",
    "import requests\n",
    "import json\n",
    "import sys\n",
    "import base64\n",
    "import time\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"log_id\":16112892907703713,\"task_status\":\"Created\",\"task_id\":\"600a52ca937f2e67595ce469\"}\n"
     ]
    }
   ],
   "source": [
    "#创建任务\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "import ssl\n",
    "ssl._create_default_https_context = ssl._create_unverified_context\n",
    "\n",
    "#填写百度控制台中相关开通了“音频文件转写”接口的应用的的API_KEY及SECRET_KEY\n",
    "API_KEY = 'kVcnfD9iW2XVZSMaLMrtLYIz'\n",
    "SECRET_KEY = 'O9o1O213UgG5LFn0bDGNtoRN3VWl2du6'\n",
    "\n",
    "\"\"\"  获取请求TOKEN start 通过开通音频文件转写接口的百度应用的API_KEY及SECRET_KEY获取请求token\"\"\"\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "TOKEN_URL = 'https://openapi.baidu.com/oauth/2.0/token'\n",
    "# SCOPE = 'brain_bicc'  # 有此scope表示有asr能力，没有请在网页里勾选 bicc\n",
    "SCOPE = 'brain_asr_async'  # 有此scope表示有asr能力，没有请在网页里勾选\n",
    "# SCOPE = 'brain_enhanced_asr'  # 有此scope表示有asr能力，没有请在网页里勾选\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode( 'utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str =  result_str.decode()\n",
    "\n",
    "#    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "#    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if not SCOPE in result['scope'].split(' '):\n",
    "            raise DemoError('scope is not correct')\n",
    "#        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\"\"\"  获取鉴权结束，TOKEN end \"\"\"\n",
    "\n",
    "\"\"\"  发送识别请求 \"\"\"\n",
    "\n",
    "#待进行语音识别的音频文件url地址，需要可公开访问。建议使用百度云对象存储（https://cloud.baidu.com/product/bos.html）\n",
    "speech_url_list = [\n",
    "    \"https://platform.bj.bcebos.com/sdk%2Fasr%2Fasr_doc%2Fdoc_download_files%2F16k.pcm\",\n",
    "    ]\n",
    "\n",
    "\n",
    "for speech_url in speech_url_list:\n",
    "\n",
    "\n",
    "    url = 'https://aip.baidubce.com/rpc/2.0/aasr/v1/create'  #创建音频转写任务请求地址\n",
    "\n",
    "    body = {\n",
    "        \"speech_url\": speech_url,\n",
    "        \"format\": \"pcm\",        #音频格式，支持pcm,wav,mp3，音频格式转化可通过开源ffmpeg工具（https://ai.baidu.com/ai-doc/SPEECH/7k38lxpwf）或音频处理软件\n",
    "        \"pid\": 1537,        #模型pid，1537为普通话输入法模型，1737为英语模型\n",
    "        \"rate\": 16000       #音频采样率，支持16000采样率，音频格式转化可通过开源ffmpeg工具（https://ai.baidu.com/ai-doc/SPEECH/7k38lxpwf）或音频处理软件\n",
    "    }\n",
    "\n",
    "    # token = {\"access_token\":\"24.19fd462ac988cb2d1cdef56fcb4b568a.2592000.1579244003.282335-11778379\"}\n",
    "\n",
    "    token = {\"access_token\":fetch_token()}\n",
    "\n",
    "    headers = {'content-type': \"application/json\"}\n",
    "\n",
    "    response = requests.post(url,params=token,data = json.dumps(body), headers = headers)\n",
    "\n",
    "    # 返回请求结果信息，获得task_id，通过识别结果查询接口，获取识别结果\n",
    "    print(response.text)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"log_id\": 16112893746713329, \"tasks_info\": [{\"task_status\": \"Success\", \"task_result\": {\"result\": [\"北京科技馆。\"], \"detailed_result\": [{\"res\": [\"北京科技馆。\"], \"end_time\": 4050, \"begin_time\": 0, \"words_info\": [], \"sn\": \"344946745971611289304\", \"corpus_no\": \"6920434866418289981\"}], \"corpus_no\": \"6920434866418289981\"}, \"task_id\": \"600a52ca937f2e67595ce469\"}]}\n"
     ]
    }
   ],
   "source": [
    "#!/usr/bin/env python\n",
    "# -*- coding: utf-8 -*-\n",
    "\n",
    "import requests\n",
    "import json\n",
    "import sys\n",
    "import base64\n",
    "import time\n",
    "\n",
    "\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "import ssl\n",
    "ssl._create_default_https_context = ssl._create_unverified_context\n",
    "\n",
    "#填写百度控制台中相关开通了“音频文件转写”接口的应用的的API_KEY及SECRET_KEY\n",
    "API_KEY = 'kVcnfD9iW2XVZSMaLMrtLYIz'\n",
    "SECRET_KEY = 'O9o1O213UgG5LFn0bDGNtoRN3VWl2du6'\n",
    "\n",
    "\n",
    "\"\"\"  获取请求TOKEN start 通过开通音频文件转写接口的百度应用的API_KEY及SECRET_KEY获取请求token\"\"\"\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "TOKEN_URL = 'https://openapi.baidu.com/oauth/2.0/token'\n",
    "# SCOPE = 'brain_bicc'  # 有此scope表示有asr能力，没有请在网页里勾选 bicc\n",
    "SCOPE = 'brain_asr_async'  # 有此scope表示有asr能力，没有请在网页里勾选\n",
    "# SCOPE = 'brain_enhanced_asr'  # 有此scope表示有asr能力，没有请在网页里勾选\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode( 'utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str =  result_str.decode()\n",
    "\n",
    "#    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "#    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if not SCOPE in result['scope'].split(' '):\n",
    "            raise DemoError('scope is not correct')\n",
    "#        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\"\"\"  获取鉴权结束，TOKEN end \"\"\"\n",
    "\n",
    "\"\"\"  发送查询结果请求 \"\"\"\n",
    "\n",
    "#转写任务id列表，task_id是通过创建音频转写任务时获取到的，每个音频任务对应的值\n",
    "task_id_list = [\n",
    "    \"600a52ca937f2e67595ce469\",\n",
    "    ]\n",
    "\n",
    "\n",
    "for task_id in task_id_list:\n",
    "\n",
    "    url = 'https://aip.baidubce.com/rpc/2.0/aasr/v1/query'  #查询音频任务转写结果请求地址\n",
    "\n",
    "    body = {\n",
    "        \"task_ids\": [task_id],\n",
    "    }\n",
    "    token = {\"access_token\":fetch_token()}\n",
    "    headers = {'content-type': \"application/json\"}\n",
    "    response = requests.post(url,params=token,data = json.dumps(body), headers = headers)\n",
    "\n",
    "\n",
    "    print(json.dumps(response.json(), ensure_ascii=False))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[\"北京科技馆。\"]\n"
     ]
    }
   ],
   "source": [
    " print(json.dumps(response.json()[\"tasks_info\"][0][\"task_result\"][\"result\"], ensure_ascii=False))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
